package com.fjc.controller;

import com.fjc.domain.Student;
import com.fjc.domain.User;
import com.fjc.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by fjc on 2018/5/22.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private StudentService studentService;

    @RequestMapping("/create")
    public String createStudent(){
        logger.info("this is a log test!!!");
        studentService.createStudent();
        return "cc";
    }

    @RequestMapping("/re")
    public String red(){
        return "redirect:/user/test";
    }

    @RequestMapping("/test")
    public ModelAndView testUser(ModelAndView modelAndView){
        modelAndView.setViewName("user");
        modelAndView.addObject("user",new User(1,"fjc"));
        return modelAndView;
    }

    @RequestMapping("/test1")
    public String testUser1(ModelMap modelMap){
        modelMap.addAttribute("user",new User(1,"fff"));
        return "user";
    }

    @RequestMapping("/save")
    public void getUser(User user){
        System.out.println(user.getName());
    }

    @RequestMapping("/json")
    @ResponseBody
    public User getUser1(@RequestBody User user){//之前的都写错了，一般哦都是用对象去装东西的
        return user;//如果返回json字符串会带有“/”,直接返回对象是没有的
    }

    @RequestMapping("/up")
    /**
     * 变量名称要和页面上的name对上
     */
    public String up(MultipartFile[] file, HttpServletRequest request) throws IOException {
        for (MultipartFile file1:file) {
            String name = file1.getOriginalFilename();
            File newFile = new File("/" + name);
            file1.transferTo(newFile);
        }
        return "user";
    }
}
